package com.hcmiu.buddytracking;

import getFromDBMethods.checkFirstLogin;
import getFromDBMethods.getAllBuddies;
import getFromDBMethods.getAllMessages;
import getFromDBMethods.getAllPOIs;
import getFromDBMethods.getCurrentUser;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import setMethods.setOnlineStatus;
import ServletProcess.checkConncetionToServer;
import Storage.Buddy;
import Storage.IconContextMenu;
import Storage.LocationOverlay;
import Storage.POI;
import Storage.PathOverlay;
import Storage.Road;
import Storage.RoadProvider;
import Utils.MyMapView;
import Utils.toastMaking;
import Utils.MyMapView.OnLongpressListener;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Map extends MapActivity {

	// ===========================================================
	// Fields
	// ===========================================================
	private Buddy buddy = null;
	private Buddy currentUser = null;
	private POI poi = null;
	private Road mRoad;

	private int refresh_interval;
	private refreshAllThread refreshMyBuddy = new refreshAllThread();
	private final int OptionsMenuID = 1;
	private final int RefreshMenuID = 2;
	private final int ModeMenuID = 4;
	private final int AddPOIMenuID = 7;
	private IconContextMenu OptionsContextMenu = null;
	private IconContextMenu RefreshContextMenu = null;
	private IconContextMenu ModeContextMenu = null;
	private IconContextMenu AddPOIContextMenu = null;

	private String currentPhoneNumber;

	private MyMapView mapView = null;
	private MyLocationOverlay whereAmI = null;

	private LocationManager locMgr = null;
	private LocationListener locListener = null;
	private List<Overlay> overlays = null;
	// GPS Listener
	private final long distanceUpdate = 2; // in Meters
	private final long timeUpdate = 5 * 1000; // in Milliseconds

	/** List of friends in */
	private ArrayList<Buddy> allBuddies = new ArrayList<Buddy>();
	/** List of message */

	private ArrayList<Storage.Message> allMessages = new ArrayList<Storage.Message>();
	private ArrayList<POI> allPOIs = new ArrayList<POI>();
	private PathOverlay pathOverlay;
	private boolean isPathDisplayed = false;
	private SharedPreferences pref;
	private String PREF_NAME = "buddytracking";

	private NotificationManager notificationManager;
	private ProgressDialog progressDialog;
	private Resources res;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// use custom title
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		buddy = new Buddy();
		poi = new POI();
		// Progress dialog
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Loading...");
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
		// progressDialog.setMax(100);
		// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.show();
		// get details pro preferences
		pref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
		currentPhoneNumber = pref.getString("currentPhoneNumber", null);

		refresh_interval = pref.getInt("refresh_interval", 10 * 1000);

		// initiate the menu
		OptionsContextMenu = new IconContextMenu(Map.this, OptionsMenuID);
		RefreshContextMenu = new IconContextMenu(Map.this, RefreshMenuID);
		ModeContextMenu = new IconContextMenu(Map.this, ModeMenuID);
		AddPOIContextMenu = new IconContextMenu(Map.this, AddPOIMenuID);
		res = getResources();
		// prepare the map
		setContentView(R.layout.map);
		// set titlebar as username
		try {
			currentUser = getCurrentUser.process(currentPhoneNumber);
			if (currentUser.getFname() != null) {
				getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
						R.layout.maptitle);
				TextView username = (TextView) getWindow().findViewById(
						R.id.username);
				username.setText(currentUser.getFullName());
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// ///////////

		mapView = (MyMapView) findViewById(R.id.geoMap);
		mapView.getController().setZoom(15);
		mapView.setBuiltInZoomControls(true);
		mapView.setClickable(true);
		mapView.setSatellite(pref.getBoolean("Satellite", false));
		mapView.setTraffic(pref.getBoolean("Traffic", false));
		mapView.setOnLongPressListener(longPressListener());
		overlays = mapView.getOverlays();
		// my location
		whereAmI = new MyLocationOverlay(getApplicationContext(), mapView);
		locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locListener = new myLocationListener();

		loadAppForFirstTime();

	}

	private void loadAppForFirstTime() {
		Thread t = new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				createAddPOIMenu();
				createOptionsMenu();
				createRefreshMenu();
				createModeMenu();
				isOnline(true);
				progressDialog.dismiss();
				refreshMyBuddy.run();
				Looper.loop();
			}
		};
		t.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		boolean supRetVal = super.onCreateOptionsMenu(menu);
		menu.add(1, 5, 0, R.string.remove_path).setIcon(R.drawable.remove_path);
		menu.add(1, 0, 1, R.string.buddylist_name).setIcon(
				R.drawable.friendlist);
		menu.add(1, 1, 2, R.string.poilist_name).setIcon(
				R.drawable.pointofinterest);
		menu.add(1, 2, 3, R.string.map_menu_send_msg).setIcon(
				R.drawable.mail_reply);
		menu.add(1, 3, 4, R.string.map_options).setIcon(R.drawable.options);
		menu.add(1, 4, 5, R.string.main_menu_exit).setIcon(R.drawable.exit);

		return supRetVal;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 0) {
			Intent i = new Intent(Map.this, BuddyList.class);
			startActivityForResult(i, R.string.buddylist);
			return true;
		}
		if (item.getItemId() == 1) {
			Intent i = new Intent(Map.this, POIList.class);
			startActivityForResult(i, R.string.poilist);
			return true;
		}
		if (item.getItemId() == 3) {
			showDialog(OptionsMenuID);
			return true;
		}
		if (item.getItemId() == 2) {
			Intent i = new Intent(Map.this, MessageBoard.class);
			startActivity(i);
			return true;

		}
		if (item.getItemId() == 4) {
			isOnline(false);
			if (pref.getBoolean("BoxChecked", false) == false) {
				pref.edit().clear().commit();
			}
			// interrupt the thread
			refreshMyBuddy.stopThread();
			if (allMessages.size() != 0)
				notificationManager.cancelAll();
			finish();
			return true;
		}
		if (item.getItemId() == 5) {
			overlays.remove(pathOverlay);
			isPathDisplayed = false;
			mapView.postInvalidate();
			return true;
		}
		return false;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (allMessages.size() != 0)
			notificationManager.cancelAll();

		locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, timeUpdate,
				distanceUpdate, locListener);
		// whereAmI.enableCompass();
		whereAmI.enableMyLocation();
		whereAmI.runOnFirstFix(new Runnable() {
			public void run() {
				mapView.getController().setCenter(whereAmI.getMyLocation());
			}
		});
		refreshMyBuddy.resumeThread();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (allMessages.size() != 0)
			notificationManager.cancelAll();

		locMgr.removeUpdates(locListener);
		// whereAmI.disableCompass();
		whereAmI.disableMyLocation();
		refreshMyBuddy.pauseThread();
	}

	Handler refreshAllHandler = new Handler() {
		/** update friend's location on every msg received */

		@Override
		public void handleMessage(Message msg) {
			refreshAll();
		}
	};

	Handler drawPathHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// remove old path
			if (pathOverlay != null) {
				overlays.remove(pathOverlay);
			}
			pathOverlay = new PathOverlay(mRoad, mapView);
			overlays.add(pathOverlay);
			isPathDisplayed = true;
			mapView.postInvalidate();
			toastMaking.infoToast(getApplicationContext(),
					"Path info: " + mRoad.mDescription).show();
		}
	};

	class refreshAllThread extends Thread {
		private boolean isRunning = false;
		private boolean isPaused = false;

		public void run() {
			isRunning = true;
			try {
				while (isRunning) {
					if (isPaused) {
						synchronized (this) {
							this.wait();
						}
					} else if (isPaused == false) {
						int rs = checkConnectionToServer();
						if (rs == 1) {							
							refreshAllHandler.sendMessage(new Message());
							Thread.sleep(refresh_interval);
						} else if (rs == 2) {							
							refreshMyBuddy.stopThread();
							createDialog("Your account is inactive");
						} else if (rs == 0) {						
							refreshMyBuddy.stopThread();
							createDialog("Server's connection was lost");
						}
					}
				}
			} catch (Exception ex) {
				// do stuff
			}
		}

		public void stopThread() {
			isRunning = false;
		}

		public void pauseThread() {
			isPaused = true;
		}

		public synchronized void resumeThread() {
			this.notify();
			isPaused = false;
		}

	}

	class myLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			// Update current user's location in DB
			try {
				ModifyLocation();
				isOnline(true);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// show your location
			showLocation(location);
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isOnline(false);
		if (pref.getBoolean("BoxChecked", false) == false) {
			pref.edit().clear().commit();
		}
		// refreshMyFriend.interrupt();
		if (allMessages.size() != 0)
			notificationManager.cancelAll();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == OptionsMenuID) {
			return OptionsContextMenu.createMenu("Options");
		}
		if (id == RefreshMenuID) {
			return RefreshContextMenu.createMenu("Refresh Intervals");
		}
		if (id == ModeMenuID) {
			return ModeContextMenu.createMenu("Map Mode");
		}
		if (id == AddPOIMenuID) {
			return AddPOIContextMenu.createMenu(null);
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean isLocationDisplayed() {
		return whereAmI.isMyLocationEnabled();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case R.string.poi_new: {
			refreshMyBuddy.resumeThread();
			if (resultCode == RESULT_OK) {
				Drawable drawable = Map.this.getResources().getDrawable(
						R.drawable.pointofinterest);
				LocationOverlay flag = new LocationOverlay(drawable,
						getApplicationContext());
				int lat = pref.getInt("POILatitude", 0);
				int log = pref.getInt("POILongitude", 0);
				String title = pref.getString("POITitle", "");
				String description = pref.getString("POIDescription", "");
				GeoPoint point = new GeoPoint(lat, log);
				flag.addOverlay(new OverlayItem(point, "Title: " + title,
						"Description: " + description));
				overlays.add(flag);
				mapView.postInvalidate();
				mapView.getController().animateTo(point);
			}
			break;
		}
		case R.string.poilist: {
			refreshMyBuddy.resumeThread();
			refreshPOI();

			if (resultCode == R.string.navigate_to_poi) {

				String poiID = data.getStringExtra("POIid");
				POI poi = new POI();
				for (POI aPOI : allPOIs) {
					if (aPOI.getPOIid().equals(poiID)) {
						poi = aPOI;
					}
				}
				mapView.getController().animateTo(poi.getGeoPoint());
			}
			if (resultCode == R.string.draw_path_to_poi) {

				String poiID = data.getStringExtra("POIid");
				for (POI aPOI : allPOIs) {
					if (aPOI.getPOIid().equals(poiID)) {
						poi = aPOI;
					}
				}

				new Thread() {
					@Override
					public void run() {
						Looper.prepare();
						Location myLocation = locMgr
								.getLastKnownLocation(LocationManager.GPS_PROVIDER);
						String url = RoadProvider.getUrl(myLocation
								.getLatitude(), myLocation.getLongitude(), poi
								.getLocation().getLatitude(), poi.getLocation()
								.getLongitude());
						InputStream is = getConnection(url);
						mRoad = RoadProvider.getRoute(is);
						if (mRoad.mDescription != null || is == null) {
							drawPathHandler.sendMessage(new Message());
						} else {
							toastMaking.infoToast(getApplicationContext(),
									"Sorry, no path was found").show();
						}
						Looper.loop();
					}
				}.start();

				mapView.getController().animateTo(poi.getGeoPoint());
				mapView.getController().setZoom(22);
			}
			break;
		}
		case R.string.buddylist: {
			refreshMyBuddy.resumeThread();
			refreshBuddy();

			if (resultCode == R.string.navigate_to_buddy) {
				int buddyID = data.getIntExtra("Buddyid", -1);
				Buddy buddy = allBuddies.get(buddyID);
				mapView.getController().animateTo(buddy.getGeoPoint());
			}

			if (resultCode == R.string.draw_path_to_buddy) {

				int buddyID = data.getIntExtra("Buddyid", -1);
				buddy = allBuddies.get(buddyID);
				new Thread() {
					@Override
					public void run() {
						Looper.prepare();
						Location myLocation = locMgr
								.getLastKnownLocation(LocationManager.GPS_PROVIDER);
						String url = RoadProvider.getUrl(myLocation
								.getLatitude(), myLocation.getLongitude(),
								buddy.getLocation().getLatitude(), buddy
										.getLocation().getLongitude());
						InputStream is = getConnection(url);
						mRoad = RoadProvider.getRoute(is);
						if (mRoad.mDescription != null || is == null) {
							drawPathHandler.sendMessage(new Message());
						} else {
							toastMaking.infoToast(getApplicationContext(),
									"Sorry, no path was found").show();
						}
						Looper.loop();
					}
				}.start();

				mapView.getController().animateTo(buddy.getGeoPoint());
				mapView.getController().setZoom(22);

			}
			break;

		}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	// ===========================================================
	// Methods
	// ===========================================================
	private boolean isFirstLogin() {
		boolean result = false;
		if (checkFirstLogin.process(currentPhoneNumber).equals("1")) {
			result = true;
		}
		return result;
	}

	private String LocationData() throws JSONException {
		JSONObject object = new JSONObject();
		Location location = locMgr
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		object.put("lat", Double.toString(location.getLatitude()));
		object.put("log", Double.toString(location.getLongitude()));
		object.put("phone", currentPhoneNumber);
		return object.toString();
	}

	private void showLocation(Location location) {
		if (location != null) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			GeoPoint myLocation = new GeoPoint((int) (lat * 1000000),
					(int) (lng * 1000000));
			mapView.getController().animateTo(myLocation);
		}
	}

	private void createAll() {

		//

		// FRIEND & MESSAGE
		try {
			allBuddies = createBuddyList();
			allMessages = createMessageList();
			allPOIs = createPOIList();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void createBuddy() {
		try {
			allBuddies = createBuddyList();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void createPOI() {
		try {
			allPOIs = createPOIList();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void refreshAll() {
		isOnline(true);
		// clear then recreate
		allBuddies.clear();
		allMessages.clear();
		allPOIs.clear();
		/*
		 * overlays.remove(displayOfflineFriend());
		 * overlays.remove(displayOnlineFriend());
		 * overlays.remove(displayPOI());
		 */
		overlays.clear();
		// mapView.invalidate();
		// reCreate
		createAll();
		// refresh navigateMenu

		// map
		if (isPathDisplayed)
			overlays.add(pathOverlay);
		overlays.add(whereAmI);

		if (displayOnlineBuddy().size() != 0)
			overlays.add(displayOnlineBuddy());
		if (displayOfflineBuddy().size() != 0)
			overlays.add(displayOfflineBuddy());
		if (displayPOI().size() != 0)
			overlays.add(displayPOI());

		// message
		displayMessages();		
		mapView.invalidate();
		// }
	}

	private void refreshBuddy() {

		// clear then recreate
		allBuddies.clear();
		overlays.clear();
		// mapView.invalidate();
		// reCreate

		createBuddy();
		// refresh navigateMenu

		// map
		if (isPathDisplayed)
			overlays.add(pathOverlay);
		overlays.add(whereAmI);

		if (displayOnlineBuddy().size() != 0)
			overlays.add(displayOnlineBuddy());
		if (displayOfflineBuddy().size() != 0)
			overlays.add(displayOfflineBuddy());
		if (displayPOI().size() != 0)
			overlays.add(displayPOI());
		// isOnline(true);
		mapView.invalidate();
		// }
	}

	private void refreshPOI() {
		// clear then recreate
		allPOIs.clear();
		overlays.clear();
		// mapView.invalidate();
		// reCreate

		createPOI();
		// refresh navigateMenu

		// map
		if (isPathDisplayed)
			overlays.add(pathOverlay);
		overlays.add(whereAmI);

		if (displayOnlineBuddy().size() != 0)
			overlays.add(displayOnlineBuddy());
		if (displayOfflineBuddy().size() != 0)
			overlays.add(displayOfflineBuddy());
		if (displayPOI().size() != 0)
			overlays.add(displayPOI());

		// isOnline(true);
		mapView.invalidate();
		// }
	}

	private void ModifyLocation() throws JSONException {
		if (isFirstLogin() == false) {
			UpdateLocation();
			toastMaking.infoToast(getApplicationContext(), "Location updated")
					.show();
		} else if (isFirstLogin() == true) {
			InsertFirstLocation();
			toastMaking.infoToast(getApplicationContext(), "Location inserted")
					.show();
		} else
			toastMaking.errorToast(getApplicationContext(),
					"cannot Insert Location").show(); // this case should never
		// be happened

	}

	private void InsertFirstLocation() throws JSONException {
		ServletProcess.LocationInsert.process(LocationData());
	}

	private void UpdateLocation() throws JSONException {
		ServletProcess.LocationUpdate.process(LocationData());
	}

	private LocationOverlay displayPOI() {
		Drawable drawable = Map.this.getResources().getDrawable(
				R.drawable.pointofinterest);
		LocationOverlay overlay = new LocationOverlay(drawable,
				getApplicationContext());
		Double lat;
		Double lng;
		GeoPoint point;
		for (POI aPOI : allPOIs) {
			if (aPOI.getIsHidden().equals("0")) {
				String title = aPOI.getPOITitle();
				lat = aPOI.getLocation().getLatitude() * 1E6;
				lng = aPOI.getLocation().getLongitude() * 1E6;
				point = new GeoPoint(lat.intValue(), lng.intValue());
				String snippet = aPOI.getMarkerName();
				overlay.addOverlay(new OverlayItem(point, title, snippet));
			}
		}
		return overlay;
	}

	private LocationOverlay displayOnlineBuddy() {
		Drawable drawable = Map.this.getResources().getDrawable(
				R.drawable.location);
		LocationOverlay overlay = new LocationOverlay(drawable,
				getApplicationContext());
		Double lat;
		Double lng;
		GeoPoint point;
		for (Buddy aBuddy : allBuddies) {
			if (aBuddy.getIsOnline().equals("1")) {
				lat = aBuddy.getLocation().getLatitude() * 1E6;
				lng = aBuddy.getLocation().getLongitude() * 1E6;
				point = new GeoPoint(lat.intValue(), lng.intValue());
				// String lastSeen = aBuddy.getLastSeen();
				String fullname = aBuddy.getFullName();
				overlay.addOverlay(new OverlayItem(point, fullname, ""));
			}
		}
		return overlay;
	}

	private LocationOverlay displayOfflineBuddy() {
		Drawable drawableOff = Map.this.getResources().getDrawable(
				R.drawable.location_off);
		LocationOverlay overlay = new LocationOverlay(drawableOff,
				getApplicationContext());
		Double lat;
		Double lng;
		GeoPoint point;

		for (Buddy aBuddy : allBuddies) {
			if (aBuddy.getIsOnline().equals("0")) {
				lat = aBuddy.getLocation().getLatitude() * 1E6;
				lng = aBuddy.getLocation().getLongitude() * 1E6;
				point = new GeoPoint(lat.intValue(), lng.intValue());

				String lastSeen = aBuddy.getLastSeen();
				String fullname = aBuddy.getFullName();
				overlay.addOverlay(new OverlayItem(point, fullname, lastSeen));
			}

		}
		return overlay;
	}

	private void displayMessages() {
		for (int i = 0; i < allMessages.size(); i++) {
			Storage.Message msg = allMessages.get(i);
			String msgid = msg.getMsgId();
			String contentTitle = msg.getSenderName();
			String contentText = msg.getMsgContent();
			addNotification(msgid, contentTitle, contentText);

		}
	}

	// get all message

	private void addNotification(String msgid, String contentTitle,
			String contentText) {
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = R.drawable.icon;
		long when = System.currentTimeMillis();

		Intent intent = new Intent(getApplicationContext(), MessageBoard.class);
		PendingIntent contentIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, intent, 0);
		Notification notification = new Notification(icon, contentTitle, when);
		/*
		 * long[] vibrate = { 0, 100, 200, 300 }; notification.vibrate =
		 * vibrate; notification.ledARGB = Color.RED; notification.ledOffMS =
		 * 300; notification.ledOnMS = 300;
		 */

		notification.defaults |= Notification.DEFAULT_LIGHTS;
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		notification.setLatestEventInfo(getApplicationContext(), contentTitle,
				contentText, contentIntent);
		notificationManager.notify(Integer.parseInt(msgid), notification);
	}

	private void isOnline(boolean result) {
		if (result == true) {
			JSONObject object = new JSONObject();
			try {
				object.put("phoneNumber", currentPhoneNumber);
				object.put("onlineStatus", "on");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			setStatus(object.toString());
		}
		if (result == false) {
			JSONObject object = new JSONObject();
			try {
				object.put("phoneNumber", currentPhoneNumber);
				object.put("onlineStatus", "off");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			setStatus(object.toString());
		}
	}

	private void setStatus(String status) {
		setOnlineStatus.process(status);
	}

	private void createOptionsMenu() {
		// create Options Context Menu
		OptionsContextMenu.addItem(res, R.string.map_options_refresh,
				R.drawable.refresh, 2);
		OptionsContextMenu.addItem(res, R.string.map_options_mode,
				R.drawable.maps, 3);
		OptionsContextMenu.addItem(res, R.string.map_options_change_password,
				R.drawable.password, 5);
		OptionsContextMenu.addItem(res, R.string.back_button, R.drawable.back,
				6);
		OptionsContextMenu
				.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
					@Override
					public void onClick(int menuId) {
						switch (menuId) {
						case 2:
							showDialog(RefreshMenuID);
							break;
						case 3:
							showDialog(ModeMenuID);
							break;
						case 5:
							startActivity(new Intent(Map.this,
									ChangePassword.class));
							break;
						case 6:
							break;
						}

					}
				});
	}

	private void createRefreshMenu() {
		RefreshContextMenu.addItem(res, "Every 30s (Default)",
				R.drawable.clock, 2);
		RefreshContextMenu.addItem(res, "Every 1min", R.drawable.clock, 3);
		RefreshContextMenu.addItem(res, "Every 2min", R.drawable.clock, 4);
		RefreshContextMenu.addItem(res, "Every 5min", R.drawable.clock, 5);
		RefreshContextMenu.addItem(res, R.string.back_button, R.drawable.back,
				6);
		RefreshContextMenu
				.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
					@Override
					public void onClick(int menuId) {
						switch (menuId) {
						case 2: {
							refresh_interval = 30 * 1000;
							pref.edit().putInt("refresh_interval",
									refresh_interval).commit();
							toastMaking
									.infoToast(getApplicationContext(),
											"Refresh interval is now set to 30 seconds")
									.show();
							break;
						}
						case 3: {
							refresh_interval = 60 * 1000;
							pref.edit().putInt("refresh_interval",
									refresh_interval).commit();
							toastMaking.infoToast(getApplicationContext(),
									"Refresh interval is now set to 1 min")
									.show();
							break;
						}
						case 4:
							refresh_interval = 2 * 60 * 1000;
							pref.edit().putInt("refresh_interval",
									refresh_interval).commit();
							toastMaking.infoToast(getApplicationContext(),
									"Refresh interval is now set to 2 mins")
									.show();
							break;
						case 5: {
							refresh_interval = 5 * 60 * 1000;
							pref.edit().putInt("refresh_interval",
									refresh_interval).commit();
							toastMaking.infoToast(getApplicationContext(),
									"Refresh interval is now set to 5mins")
									.show();
							break;
						}
						case 6: {
							showDialog(OptionsMenuID);
							break;
						}
						}
					}
				});

	}

	private void createModeMenu() {
		ModeContextMenu.addItem(res, "Normal", R.drawable.map_normal, 1);
		ModeContextMenu.addItem(res, "Toggle Satellite",
				R.drawable.map_satellite, 2);
		ModeContextMenu.addItem(res, "Toogle Traffic", R.drawable.map_traffic,
				3);
		ModeContextMenu.addItem(res, R.string.back_button, R.drawable.back, 4);
		ModeContextMenu
				.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
					@Override
					public void onClick(int menuId) {
						switch (menuId) {
						case 1:
							mapView.setSatellite(false);
							pref.edit().putBoolean("Satellite", false)
									.putBoolean("Traffic", false).commit();
							mapView.setTraffic(false);
							toastMaking.infoToast(getApplicationContext(),
									"Normal View is selected").show();
							break;
						case 2:
							if (mapView.isSatellite()) {
								mapView.setSatellite(false);
								pref.edit().putBoolean("Satellite", false)
										.commit();
								toastMaking.infoToast(getApplicationContext(),
										"Satellite View is removed").show();
							} else {
								mapView.setSatellite(true);
								pref.edit().putBoolean("Satellite", true)
										.commit();
								toastMaking.infoToast(getApplicationContext(),
										"Satellite View is selected").show();
							}

							break;
						case 3:
							if (mapView.isTraffic()) {
								mapView.setTraffic(false);
								pref.edit().putBoolean("Traffic", false)
										.commit();
								toastMaking.infoToast(getApplicationContext(),
										"Traffic View is removed").show();
							} else {
								mapView.setTraffic(true);
								pref.edit().putBoolean("Traffic", true)
										.commit();
								toastMaking.infoToast(getApplicationContext(),
										"Traffic View is selected").show();
							}
							break;
						case 4:
							showDialog(OptionsMenuID);
							break;
						}
					}
				});
	}

	private void createAddPOIMenu() {

		// create Options Context Menu
		AddPOIContextMenu.addItem(res, "Mark this location",
				R.drawable.pointofinterest, 2);
		AddPOIContextMenu
				.addItem(res, R.string.back_button, R.drawable.back, 3);
		AddPOIContextMenu
				.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
					@Override
					public void onClick(int menuId) {
						switch (menuId) {
						case 2:
							Intent i = new Intent(Map.this, AddPOI.class);
							startActivityForResult(i, R.string.poi_new);
							break;
						case 3:
							break;
						}

					}
				});
	}

	private OnLongpressListener longPressListener() {
		return new OnLongpressListener() {
			public void onLongpress(final MapView view,
					final GeoPoint longpressLocation) {
				runOnUiThread(new Runnable() {
					public void run() {
						pref.edit().putInt("POILatitude",
								longpressLocation.getLatitudeE6()).putInt(
								"POILongitude",
								longpressLocation.getLongitudeE6()).commit();
						showDialog(AddPOIMenuID);
					}
				});

			}
		};
	}

	private ArrayList<Buddy> createBuddyList() throws JSONException {
		return allBuddies = getAllBuddies.process(currentPhoneNumber);

	}

	private ArrayList<Storage.Message> createMessageList() throws JSONException {
		JSONObject object = new JSONObject();
		object.put("currentPhoneNumber", currentPhoneNumber);
		object.put("refresh_interval", refresh_interval);
		return allMessages = getAllMessages.process(object.toString());
	}

	private ArrayList<POI> createPOIList() throws JSONException {
		return allPOIs = getAllPOIs.process(currentPhoneNumber);
	}

	private int checkConnectionToServer() {
		String rs  = checkConncetionToServer.process(currentPhoneNumber);
		if (rs.equals("1"))
			return 1;
		else if (rs.equals("2"))
			return 2;
		else
			return 0;
	}

	private void createDialog(String content) {
		AlertDialog ad = new AlertDialog.Builder(this).setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (allMessages.size() != 0)
						notificationManager.cancelAll();
						
						finish();
					}
				}).setTitle("Error").setMessage(content).create();
		ad.show();
	}

	private InputStream getConnection(String url) {
		InputStream is = null;
		try {
			URLConnection conn = new URL(url).openConnection();
			is = conn.getInputStream();
		} catch (MalformedURLException e) {
			is = null;
		} catch (IOException e) {
			is = null;
		}
		return is;
	}
}
